package com.melihelibol.stratosphere.net {
	
	/*
	Copyright (c) <2009> <copyright H. Melih Elibol>
	
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
	*/
	
	import __AS3__.vec.Vector;
	
	import com.melihelibol.stratosphere.Stratosphere;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.*;
	
	public class PeerConnections extends EventDispatcher {
		
		public static const NETWORK_NAME:String = "com.melihelibol.stratosphere";
		
		public static const INIT_CONNECTION_COMPLETE:String = "initConnectionComplete";
		public static const INIT_SEND_STREAM_COMPLETE:String = "initSendStreamComplete";
		public static const INIT_RECIEVE_STREAM_COMPLETE:String = "initRecieveStreamComplete";
		
		public static const INIT_CONNECTION:String = "initConnection";
		public static const INIT_SEND_STREAM:String = "initSendStream";
		public static const INIT_RECIEVE_STREAM:String = "initRecieveStream";
		public static const CONNECTED:String = "connected";
		
		private var stratosphere:Stratosphere;
		
		private var nc:NetConnection;
		
		private var sendStream:NetStream;
		private var sendStreamClient:Object;
		
		private var recieveStreams:Vector.<NetStream>;
		private var recieveStreamClient:Object;
		
		private var connectionChanged:Boolean = false;
		private var sendStreamChanged:Boolean = false;
		private var recieveStreamChanged:Boolean = false;
		
		public var phase:String;
		public var peerID:String;
		
		public function PeerConnections(stratosphere:Stratosphere) {
			this.stratosphere = stratosphere;
		}
		
		private function init():void {
			recieveStreams = new Vector.<NetStream>();
			recieveStreamClient = new Object();
		}
		
		public function open():void {
			connectionChanged = true;
			phase = INIT_CONNECTION;
			nc = new NetConnection();
			nc.addEventListener(NetStatusEvent.NET_STATUS, connectionStatus);
			nc.connect(Stratosphere.SERVER_ADDRESS+stratosphere.developerKey);
		}
		
		public function receiveConnection(remotePeerID:String):void {
			newRecieveStream(remotePeerID);
		}
		
		private function initSendStream():void {
			sendStreamChanged = true;
			phase = INIT_SEND_STREAM;
			sendStream = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
			sendStream.addEventListener(NetStatusEvent.NET_STATUS, sendStatus);
			sendStream.publish(NETWORK_NAME);
			sendStreamClient = new Object();
			sendStreamClient.onPeerConnect = sendStreamOnPeerConnect;
			sendStream.client = sendStreamClient;
		}
		
		private function sendStatus(e:NetStatusEvent):void {
			trace("connectionStatus", e.info.code);
			if(sendStreamChanged){
				sendStreamChanged = false;
				phase = INIT_SEND_STREAM_COMPLETE;
				dispatchEvent(new Event(INIT_SEND_STREAM_COMPLETE));
			}
		}
		
		private function newRecieveStream(remotePeerID:String):void {
			recieveStreamChanged = true;
			var recieveStream:NetStream;
			recieveStream = new NetStream(nc, remotePeerID);
			recieveStreams.push(recieveStream);
			recieveStream.addEventListener(NetStatusEvent.NET_STATUS, recieveStatus);
			recieveStream.play(NETWORK_NAME);
			recieveStream.client = recieveStreamClient;
		}
		
		private function connectionStatus(e:NetStatusEvent):void {
			trace("connectionStatus", e.info.code);
			if(connectionChanged){
				connectionChanged = false;
				dispatchEvent(new Event(INIT_CONNECTION_COMPLETE));
				phase = INIT_CONNECTION_COMPLETE;
			}
		}
		
		private function recieveStatus(e:NetStatusEvent):void {
			trace("connectionStatus", e.info.code);
			if(recieveStreamChanged){
				recieveStreamChanged = false;
				phase = INIT_RECIEVE_STREAM_COMPLETE;
				dispatchEvent(new Event(INIT_RECIEVE_STREAM_COMPLETE));
				phase = CONNECTED;
			}
		}
		
		/**
		 * Stream Handlers
		 */
		
		/* 
		private function connectionStatus(e:NetStatusEvent):void {
			trace("connectionStatus", e.info.code);
			try {
				phaseComplete();
			} catch(e:Error){
				trace(e);
			}
		}
		
		private function recieveStatus(e:NetStatusEvent):void {
			trace("recieveStatus", e.info.code);
			try {
				phaseComplete();
			} catch(e:Error){
				trace(e);
			}
		}
		
		private function sendStatus(e:NetStatusEvent):void {
			trace("sendStatus", e.info.code);
			try {
				phaseComplete();
			} catch(e:Error){
				trace(e);
			}
		}
		
		private function phaseComplete():void {
			trace("phase", phase);
			switch(phase){
				case INIT_CONNECTION:
					localPeerID = nc.nearID;
					dispatchEvent(new Event(INIT_CONNECTION_COMPLETE));
					phase = INIT_CONNECTION_COMPLETE;
					initSendStream();
					break;
				case INIT_SEND_STREAM:
					phase = INIT_SEND_STREAM_COMPLETE;
					dispatchEvent(new Event(INIT_SEND_STREAM_COMPLETE));
					break;
				case INIT_RECIEVE_STREAM:
					phase = INIT_RECIEVE_STREAM_COMPLETE;
					dispatchEvent(new Event(INIT_RECIEVE_STREAM_COMPLETE));
					phase = CONNECTED;
					break;
				case CONNECTED:
					dispatchEvent(new Event(Event.CHANGE));
					break;
				default:
					break;
			}
		}
		 */
		
		private function sendStreamOnPeerConnect(callerNS:NetStream):Boolean {
			remotePeerID = callerNS.farID;
			callerNS.peerStreams;
			if(phase == INIT_SEND_STREAM_COMPLETE) {
				//this is the end that did not initiate the connection
				newRecieveStream();
			}
			return true;
		}
		
		/**
		 * Handler API
		 */
		 
		public function addMessageHandler(name:String, handler:Function):void {
			recieveStreamClient[name] = handler;
		}
		
		public function removeMessageHandler(name:String):void {
			delete recieveStreamClient[name];
		}
		
		public function send(message:String, ...args):void {
			sendStream.send(message, args);
		}
		
	}
	
}